package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.alibaba.fastjson.JSONObject;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessRongIM;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.UserInfoVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.ExpertInfoXML;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.UserXML;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;



/**
 * ================================================
 * 项目名称：BigData
 * 类描述：融云会话页面
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/2/7 15:05
 * 修改备注：
 * ================================================
 */

public class ConversationActivity extends BaseActivity {

    /**
     * 目标 Id
     */
    private String mTargetId;

    private String title;
    private String keyWord;
    private String path;
    private String firstAskTime;
    private String assessId;

    private Handler mWorkHandler;
    private HandlerThread mWorkThread;
    private String msgType = "";
    private boolean isExpert = true; // 是否从专家咨询过来

    private String extra = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.conversation);
    }

    @Override
    public void initMember() {

        String name = "";
        String img = "";
        if (UserXML.getUserType(this).equals(Constant.USER_TYPE_EXPERT)) {
            //专家用户
            name = ExpertInfoXML.getExpertName(this);
            img = URL.URL_SHOW_IMAGE + ExpertInfoXML.getPhoto(ConversationActivity.this) + Constant.SHOW_IMAGE_TYPE_MID;
        } else {
            //个人用户
            if (!StringUtil.isStrEmpty(PersonalInfoXML.getTrueName(this)))
                name = PersonalInfoXML.getTrueName(this);
            else if(!StringUtil.isStrEmpty(PersonalInfoXML.getNiceName(this)))
                name = PersonalInfoXML.getNiceName(this);
            else
                name = UserXML.getUseraccName(this);

            img = URL.URL_SHOW_IMAGE + PersonalInfoXML.getHeadportrait(ConversationActivity.this) + Constant.SHOW_IMAGE_TYPE_MID;

        }

        UserInfoVO userInfo = new UserInfoVO();
        userInfo.setId(UserXML.getUserId(this));
        userInfo.setName(name);
        userInfo.setPortraitUri(img);
        extra = "{userInfo:" + JSONObject.toJSONString(userInfo) + "}";


        Intent intent = getIntent();
        if (null == intent || intent.getData() == null)
            return;

        if (intent.hasExtra("map")) {

            Map<String, String> map = (Map<String, String>) getIntent().getSerializableExtra("map");

            mTargetId = map.get("targetId");
            title = map.get("title");
            isExpert = false;
            setTitle(title);
        } else {
            mTargetId = intent.getData().getQueryParameter("targetId");
            String complexTitle = intent.getData().getQueryParameter("title");

            if (complexTitle.contains("&")) {
                String[] data = complexTitle.split("&");
                if (data.length == 1) {
                    title = data[0];
                    keyWord = "";
                } else if (data.length == 2) {
                    title = data[0];
                    keyWord = data[1];
                } else if (data.length == 3) {
                    title = data[0];
                    keyWord = data[1];
                    path = data[2];
                }
            } else
                title = complexTitle;


            if (title.length() > 3) {
                String s = title.substring(title.length() - 3);
                if (s.equals("nhb")) {
                    isExpert = false;
                    title = title.substring(0, title.length() - 3);
                }
            }

            setTitle(title);
            MyThread m = new MyThread();
            new Thread(m).start();
        }
    }


    private class MyThread extends Thread {

        public void run() {
            Looper.prepare();
            if (!StringUtil.isStrEmpty(keyWord))
            if (!StringUtil.isStrEmpty(path)) {
                if (path.contains(",")) {
                    String paths[] = path.split(",");
                    for (int i = 0; i < paths.length; i++) {
                        sendImageMessage(paths[i], i + 1);
                    }
                } else
                    sendImageMessage(path, 1);
            }
        }
    }



    String targetId = "";

    @Override
    public void addListener() {


    }



    /**
     * 将系统表情转化为字符串
     *
     * @param s
     * @return
     */
    public static String getString(String s) {
        int length = s.length();
        String context = "";
        //循环遍历字符串，将字符串拆分为一个一个字符
        for (int i = 0; i < length; i++) {
            char codePoint = s.charAt(i);
            //判断字符是否是emoji表情的字符
            if (isEmojiCharacter(codePoint)) {
                //如果是将以大括号括起来
                String emoji = "{" + Integer.toHexString(codePoint) + "}";
                context = context + emoji;
                continue;
            }
            context = context + codePoint;
        }
        return context;
    }

    /**
     * 是否包含表情
     *
     * @param codePoint
     * @return 如果不包含 返回false,包含 则返回true
     */

    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    // 发送图片消息。

    // 发送图片消息。
    private void sendImageMessage(String imgPath, int size) {


        File imageFileSource = new File(getCacheDir(), "source" + size + ".jpg");
        File imageFileThumb = new File(getCacheDir(), "thumb" + size + ".jpg");

        try {
            // 读取图片。
//            InputStream is = getAssets().open("emmy.jpg");
//            InputStream is = getContentResolver().openInputStream(Uri.parse(imgPath));
            InputStream is = getContentResolver().openInputStream(Uri.fromFile(new File(imgPath)));

            Bitmap bmpSource = BitmapFactory.decodeStream(is);

            imageFileSource.createNewFile();

            FileOutputStream fosSource = new FileOutputStream(imageFileSource);

            // 保存原图。
            bmpSource.compress(Bitmap.CompressFormat.JPEG, 100, fosSource);

            // 创建缩略图变换矩阵。
            Matrix m = new Matrix();
            m.setRectToRect(new RectF(0, 0, bmpSource.getWidth(), bmpSource.getHeight()), new RectF(0, 0, 160, 160), Matrix.ScaleToFit.CENTER);

            // 生成缩略图。
            Bitmap bmpThumb = Bitmap.createBitmap(bmpSource, 0, 0, bmpSource.getWidth(), bmpSource.getHeight(), m, true);

            imageFileThumb.createNewFile();

            FileOutputStream fosThumb = new FileOutputStream(imageFileThumb);

            // 保存缩略图。
            bmpThumb.compress(Bitmap.CompressFormat.JPEG, 60, fosThumb);

        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    /**
     * 保存聊天记录
     *
     * @param targetId   消息接受者ID
     * @param msgContent 消息内容
     */
    private void saveMessageInfo(String targetId, String msgContent) {
        BusinessRongIM.addMessageInfo(ConversationActivity.this, targetId, msgContent, mHandler);
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片完毕
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "fileStorage", FileVO.class);
                        if (fileVO == null || msgType.equals(""))
                            return;
                        if (msgType.equals("2")) {
                            LogUtils.e("保存图片记录" + fileVO.getName());
                            // 保存图片到聊天记录
                            BusinessRongIM.addImageMessageInfo(ConversationActivity.this, targetId, fileVO.getName(), mHandler);
                        } else {
                            LogUtils.e("保存语音记录" + fileVO.getName());
                            // 保存图片到聊天记录
                            BusinessRongIM.addVoiceMessageInfo(ConversationActivity.this, targetId, fileVO.getName(), mHandler);
                        }
                        msgType = "";
                        break;
                    case MSG.MSG_ADD_MESSAGE_INFO_SUCCESS:
                        LogUtils.e(msg.obj);
                        break;
                    case MSG.MSG_GET_ASSESS_ID_SUCCESS:
                        LogUtils.e(msg.obj);
                        assessId = FastJsonUtil.getString(msg.obj.toString(), "assessId");
                        break;
                }
            }
        };
    }


    @Override
    public void callBack(Object object) {
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * unicode的String转换成String的字符串
     *
     * @param hex 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串
     */
    public static String unicodeToString1(String hex) {
        int t = hex.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }


    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return android.util.Base64.encodeToString(buffer, android.util.Base64.DEFAULT);
    }
}
